<template lang="pug">
  el-drawer.commonDrawer(
    :title="`${operateType === 'add' ? '新增' : operateType === 'update' ? '修改' : '查看'}自建课程`"
    :visible.sync="visibleDialog"
    v-loading="loading"
    custom-class="commonDrawer"
    direction="rtl"
    size="640px"
    append-to-body
    destroy-on-close
    modal-append-to-body
  )
    .drawer-content
      form-box(
        ref="form"
        :fields="basicFormFields"
        :showBtns="false"
        labelWidth="126px"
        :disabled="disabled"
        :layoutCol="{ sm: 24, md: 24, lg: 24 }"
        @inputChange="inputChange"
      )
        template(slot="form-monthRange")
          el-select(v-model="info.beginMonth" style="width: 104px")
            el-option(
              v-for="index in 48"
              :disabled="index > info.endMonth"
              :key="index"
              :value="index"
              :label="`${index}月`"
            )
          small(class="ml5 mr5") 至
          el-select(v-model="info.endMonth" style="width: 104px")
            el-option(
              v-for="index in 48"
              :disabled="index < info.beginMonth"
              :key="index"
              :value="index"
              :label="`${index}月`"
            )
    .drawer-footer.tr(v-if="!disabled")
      el-button(size="large" round :loading="submitting" @click="$_handleCancel") 取消
      el-button.gradientVertical(size="large" round :loading="submitting" @click="submitHandle") 确定
</template>
<script>
import { mapGetters } from 'vuex'
import { getInfo, getTypes, createType, createInfo } from './api'
import omit from 'lodash/omit'

export default {
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    operateType: {
      default: 'add',
      type: String
    },
    id: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      submitting: false,
      loading: false,
      info: {
        beginMonth: 0,
        endMonth: 48,
        fileUrl: ''
      },
      types: []
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    disabled () {
      return this.operateType === 'view'
    },
    basicFormFields () {
      const { info, types } = this

      const list = [
        {
          key: 'name',
          label: '课程名称',
          rules: [{ required: true, message: '请输入' }],
          initialValue: info.name
        },
        {
          key: 'typeId',
          label: '课程分类',
          type: 'select',
          fieldProps: {
            options: types,
            props: {
              label: 'typeName'
            },
            helpHtml: '添加分类',
            helpHandle: () => this.addTypes()
          },
          rules: [{ required: true, message: '请输入' }],
          initialValue: info.typeId
        },
        {
          key: 'monthRange',
          type: 'slot',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          label: '适用月龄',
          rules: [{ required: true, message: '请输入' }],
          initialValue: `${info?.beginMonth} ~ ${info?.endMonth}`
        },
        {
          key: 'content',
          label: '课程内容',
          type: 'editor',
          rules: [{ required: true, message: '请输入' }],
          fieldProps: {
            mode: 'wysiwyg'
          },
          initialValue: info.content
        },
        {
          key: 'status',
          label: '是否启用',
          type: 'switch',
          initialValue: info.status === 0
        },
        {
          key: 'fileList',
          label: '课程附件',
          type: 'upload',
          rules: [{ required: true, message: '请输入' }],
          initialValue: info.fileList || []
        }
      ]
      const validTypes = ['add', 'update']
      validTypes.includes(this.operateType.toLowerCase())
        ? list.splice(5, 0, {
          key: 'fileURl',
          label: '课程附件地址',
          initialValue: '',
          flag: true,
          fieldProps: {
            maxlength: 1000
          }
        })
        : ''
      return list
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.getInfo()
      }
    }
  },
  created () {
    this.getTypes()
  },
  methods: {
    async getInfo () {
      const { id } = this
      if (id) {
        this.loading = true
        this.info = (await getInfo({ courseId: this.id })) || {}
        this.info.fileList = JSON.parse(this.info.attachments)
        this.loading = false
      } else {
        this.info = {}
      }
    },
    async getTypes () {
      const { curArea } = this
      this.types = (await getTypes({ areaId: curArea.areaId })) || {}
    },
    addTypes () {
      const that = this
      this.$prompt('请输入课程分类', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        createType({
          status: 0,
          typeName: value,
          type: 2,
          templateType: 3
        }).then(() => {
          that.$message.success('添加分类成功')
          that.getTypes()
        })
      })
    },

    async submitHandle () {
      const values = await this.$refs.form.submitForm()
      if (
        !Object.prototype.hasOwnProperty.call(this.info, 'beginMonth') ||
        !Object.prototype.hasOwnProperty.call(this.info, 'endMonth')
      ) {
        this.$message.error('请选择适用月龄')
        return
      }
      const { beginMonth, endMonth } = this.info
      const { id } = this
      const { fileList, status } = values
      let fileFlag = true
      fileList.forEach((x) => {
        if (x.status !== 'success') {
          fileFlag = false
        }
      })
      if (!fileFlag) {
        this.$message.warning('文件还未上传完成，请稍后保存')
        return
      }
      const params = {
        courseAreaVo: {
          ...omit(values, ['monthRange', 'fileList', 'status']),
          beginMonth,
          endMonth,
          status: status ? 0 : 1,
          courseId: id || null
        },
        attachments: fileList
      }
      console.log(params)
      this.submitting = true
      createInfo(params)
        .then((res) => {
          if (res) {
            this.$message.success('保存成功')
            this.$emit('getList')
            this.$_handleCancel()
          }
        })
        .finally(() => {
          this.submitting = false
        })
    },

    inputChange (e) {
      if (e === '') return
      // 获取子组件引用并修改其数据
      this.$refs.form.formData.fileList = [
        {
          name: e,
          status: 'success',
          type: 'video',
          url: e
        }
      ]
    },

    $_handleCancel () {
      this.visibleDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  padding: 0 24px;
  height: calc(100vh - 76px);
  overflow-y: auto;
}
</style>
